<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col class="card-box">
        <el-card shadow="hover" v-loading="pd.reloading.firstReloading">
          <template #header>
            <el-col style="display: flex;justify-content: space-between">
              <el-row>
                <el-radio-group v-model="msgSelect">
                  <el-badge :value="pd.msg.msgCount[0].num">
                    <el-radio-button label="销售新增"/>
                  </el-badge>
                  <el-badge :value="pd.msg.msgCount[1].num">
                    <el-radio-button label="退货新增"/>
                  </el-badge>
                  <el-badge :value="pd.msg.warnMsgCount.stockWarnMsg.num">
                    <el-radio-button label="预警信息"/>
                  </el-badge>
                </el-radio-group>
              </el-row>
              <el-row style="margin-top: -7px" v-if="msgSelect!='预警信息'">
                <el-radio-group v-model="msgDateSelect" is-button>
                  <el-radio-button label="近一周" />
                  <el-radio-button label="近一月" />
                  <el-radio-button label="近一年" />
                </el-radio-group>
                <el-button icon="Refresh" circle @click="firstRefresh" style="margin-top: 4px"/>
              </el-row>
            </el-col>
          </template>
          <el-col style="display: flex;">
            <el-row v-if="msgSelect=='销售新增'">
              <el-button @click="route('/crm/salesOrder/retail14',
              {
                  typeId:14,
                  status:1,
                  beginUpdateTime:pd.msg.queryParams.params.beginCreateTime,
                  endUpdateTime:pd.msg.queryParams.params.endCreateTime,
                })" type="primary" plain>
                <el-icon><ShoppingCart /></el-icon>
                <p style="margin: 0 50px 0 10px">零售订单</p>
                <p>{{ pd.msg.inOutCount.msg1[0].num }}</p>
              </el-button>
              <el-button @click="route('/crm/salesOrder/stockOut8',
              {
                  typeId:8,
                  status:1,
                  beginUpdateTime:pd.msg.queryParams.params.beginCreateTime,
                  endUpdateTime:pd.msg.queryParams.params.endCreateTime,
                })" type="primary" plain>
                <el-icon><ShoppingCart /></el-icon>
                <p style="margin: 0 50px 0 10px">库存销售单</p>
                <p>{{ pd.msg.inOutCount.msg1[1].num }}</p>
              </el-button>
              <el-button @click="route('/crm/salesOrder/service5',
              {
                  typeId:6,
                  status:1,
                  beginUpdateTime:pd.msg.queryParams.params.beginCreateTime,
                  endUpdateTime:pd.msg.queryParams.params.endCreateTime,
                })" type="primary" plain>
                <el-icon><ShoppingCart /></el-icon>
                <p style="margin: 0 50px 0 10px">服务订单</p>
                <p>{{ pd.msg.inOutCount.msg1[2].num }}</p>
              </el-button>
              <el-button @click="route('/wms/per/purchase',
              {
                  typeId:22,
                  status:1,
                  beginUpdateTime:pd.msg.queryParams.params.beginCreateTime,
                  endUpdateTime:pd.msg.queryParams.params.endCreateTime,
                })" type="primary" plain>
                <el-icon><ShoppingCart /></el-icon>
                <p style="margin: 0 50px 0 10px">入库采购订单</p>
                <p>{{ pd.msg.inOutCount.msg1[3].num }}</p>
              </el-button>
            </el-row>

            <el-row v-if="msgSelect=='退货新增'">
              <el-button @click="route('/crm/salesOrder/retail15',
              {
                  typeId:15,
                  status:1,
                  beginUpdateTime:pd.msg.queryParams.params.beginCreateTime,
                  endUpdateTime:pd.msg.queryParams.params.endCreateTime,
                })" type="primary" plain>
                <el-icon><ShoppingCart /></el-icon>
                <p style="margin: 0 50px 0 10px">零售退货订单</p>
                <p>{{ pd.msg.inOutCount.msg1[4].num }}</p>
              </el-button>
              <el-button @click="route('/crm/salesOrder/seals9',
              {
                  typeId:9,
                  status:1,
                  beginUpdateTime:pd.msg.queryParams.params.beginCreateTime,
                  endUpdateTime:pd.msg.queryParams.params.endCreateTime,
                })" type="primary" plain>
                <el-icon><ShoppingCart /></el-icon>
                <p style="margin: 0 50px 0 10px">库存退货单</p>
                <p>{{ pd.msg.inOutCount.msg1[5].num }}</p>
              </el-button>
              <el-button @click="route('/crm/salesOrder/service7',
              {
                  typeId:7,
                  status:1,
                  beginUpdateTime:pd.msg.queryParams.params.beginCreateTime,
                  endUpdateTime:pd.msg.queryParams.params.endCreateTime,
                })" type="primary" plain>
                <el-icon><ShoppingCart /></el-icon>
                <p style="margin: 0 50px 0 10px">服务退销单</p>
                <p>{{ pd.msg.inOutCount.msg1[6].num }}</p>
              </el-button>
              <el-button @click="route('/wms/per/purchaseBack',
              {
                  typeId:23,
                  status:1,
                  beginUpdateTime:pd.msg.queryParams.params.beginCreateTime,
                  endUpdateTime:pd.msg.queryParams.params.endCreateTime,
                })" type="primary" plain>
                <el-icon><ShoppingCart /></el-icon>
                <p style="margin: 0 50px 0 10px">采购退货单</p>
                <p>{{ pd.msg.inOutCount.msg1[7].num }}</p>
              </el-button>
            </el-row>

            <el-row v-if="msgSelect=='预警信息'">
              <el-button @click="route('/wms/st/wtockWarning',
              {})" type="primary" plain>
                <el-icon><ShoppingCart /></el-icon>
                <p style="margin: 0 50px 0 10px">库存预警</p>
                <p>{{ pd.msg.warnMsgCount.stockWarnMsg.num }}</p>
              </el-button>
            </el-row>
          </el-col>
        </el-card>
      </el-col>
      <el-col class="card-box">
        <el-card shadow="hover" v-loading="pd.reloading.secondReloading">
          <template #header>
            <el-col style="display: flex;justify-content: space-between">
              <el-row style="margin-top: -7px">
                <el-radio-group v-model="typeSelect" is-button>
                  <el-radio-button label="销货"/>
                  <el-radio-button label="购货"/>
                </el-radio-group>
              </el-row>
              <el-row style="margin-top: -7px">
                <el-radio-group v-model="dateSelect" is-button>
                  <el-radio-button label="近一周" />
                  <el-radio-button label="近一月" />
                  <el-radio-button label="近一年" />
                </el-radio-group>
                <el-button icon="Refresh" circle @click="secondRefresh"/>
              </el-row>
            </el-col>
          </template>
          <div style="display: flex; height: 400px">
            <div style="width: 100%; height: 100%; max-width: 1200px;">
              <div ref="orderSale" style="height: 400px" />
            </div>
            <el-card shadow="none" style="border: none;width: 100%;max-width: 420px">
              <p style="font-weight: 800;font-size: 15px;margin-top: 0;">单品金额排名</p>
              <el-table :data="pd.productSort" style="height: 340px;width: 100%; min-width: 300px;">
                <el-table-column type="index" :index="indexMethod" align="center"/>
                <el-table-column prop="productName" label="产品名称" style="max-width: 150px" />
                <el-table-column prop="costMoney" label="销售额" :formatter="formatter" align="right" style="max-width: 150px" />
              </el-table>
            </el-card>
          </div>
        </el-card>
      </el-col>
      <el-col class="card-box">
        <el-card shadow="hover" v-loading="pd.reloading.thirdReloading">
        <div style="display: flex;">
          <el-card shadow="never" class="divCard">
              <div style="max-width: 600px; height: 100%; ">
                <div ref="stockPie" style="height: 500px" />
              </div>
          </el-card>
          <el-card shadow="never" class="divCard" style="position: relative">
            <el-radio-group v-model="billDateSelect" is-button style="position: absolute;z-index: 1; right:0">
              <el-radio-button label="近一周" />
              <el-radio-button label="近一月" />
              <el-radio-button label="近一年" />
            </el-radio-group>
            <div style="max-width: 600px; height: 100%;">
              <div ref="billPie" style="height: 500px" />
            </div>
          </el-card>
          <el-card shadow="never" class="divCard" style="position: relative">
            <div style="width: 100%; height: 100%; max-width: 600px;">
              <div ref="accountBar" style="height: 500px" />
            </div>
          </el-card>
          <el-button icon="Refresh" circle @click="thirdRefresh"/>
        </div>
        </el-card>
      </el-col>
    </el-row>
    <el-divider />
  </div>
</template>

<script setup name="Index" lang="ts">
import * as echarts from 'echarts';
import {
  billList,
  getBillList, getFmsAccount,
  getOrderList,
  getOrderMsgList,
  getProductOrderSort,
  getStockList,
  getWWP,
  orderList
} from "@/views/report/api";
import {ShoppingCart} from "@element-plus/icons-vue";

const router = useRouter();

// 柱状图
const orderSale = ref();
const typeSelect = ref("销货");
const dateSelect = ref("近一周");

const msgSelect = ref("销售新增");
const msgDateSelect = ref("近一周");

// 库存饼状图
const stockPie = ref();
// 收支饼状图
const billPie = ref();
const billDateSelect = ref("近一周");
// 账户余额柱状图
const accountBar = ref();

const indexMethod = (index: number) => {
  return index + 1
}

const pd = reactive({
  reloading: {
    firstReloading: false,
    secondReloading: false,
    thirdReloading: false,
  },
  location:500,
  saleId:[6,8,14],
  buyId:[22],
  orderSaleLine: <any>({
    totalMoney:[],
    discountMoney:[],
    costMoney:[],
  }),
  orderBuyLine: <any>({
    totalMoney:[],
    discountMoney:[],
    costMoney:[],
  }),
  orderList: <orderList[]>[],
  productSort: <orderList[]>[],
  queryParams: <orderList>{
    dateRange: '%Y-%m-%d',
    params:{
      beginCreateTime: null,
      endCreateTime: null,
    }
  },
  instance: {
    yAxisMax: 0,
    yAxisMin: 0,
    data: <any[]>[],
  },
  msg:{
    queryParams: <orderList>{
      dateRange: '%Y-%m-%d',
      params:{
        beginCreateTime: null,
        endCreateTime: null,
      }
    },
    msgId:{
      msgId:[6,8,14,22,7,9,15,23],
    },
    msgCount: [
      {num: 0,typeId:[6,8,14,22]},
      {num: 0,typeId:[7,9,15,23]},
    ],
    inOutCount:{
      msg1:[
        {order: 14,num: 0,},
        {order: 8,num: 0,},
        {order: 6,num: 0,},
        {order: 22,num: 0,},
        {order: 15,num: 0,},
        {order: 9,num: 0,},
        {order: 7,num: 0,},
        {order: 23,num: 0,},
    ],
    },
    warnMsgCount:{
      stockWarnMsg:{num: 0,},
    },
  },
  stockPie:{
    stockList:[]
  },
  billPie:{
    billQueryParams:<billList>{
      params:{
        beginCreateTime: null,
        endCreateTime: null,
      }
    },
    billList:[]
  },
  accountBar:{
    xAxisData:<any[]>[],
    seriesData:<any[]>[],
  }
})

/**
 * 柱状图
 * */
let saleInstanceBar = <any>({});
function barSet(){
  saleInstanceBar = echarts.init(orderSale.value);
  saleInstanceBar.setOption({
    legend: {
      data: ["总金额", "优惠金额", "实际金额"]
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    tooltip : {
      trigger: 'axis',
    },
    calculable : true,
    xAxis : [
      {
        type : 'category',
        data : pd.instance.data,
      }
    ],
    yAxis : [
      {
        type : 'value',
        axisLabel : {
          formatter: '{value} ￥'
        },
        splitLine :{
          lineStyle:{
            type:'dashed'
          },
        }
      }
    ],
    barMaxWidth: 40,
    itemStyle:{
      borderRadius:[5, 5 , 0, 0],
    },
    series : [
      {
        color: '#5370C4',
        name: '总金额',
        type:'bar',
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
        },
        data: pd.orderSaleLine.totalMoney,
      },{
        color: '#91CD77',
        name: '优惠金额',
        type:'bar',
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
        },
        data: pd.orderSaleLine.discountMoney,
      },{
        color: '#64b7f3',
        name: '实际金额',
        type:'bar',
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
        },
        data: pd.orderSaleLine.costMoney,
      },
    ]
  });
}

window.onresize = function() {
  // 让图表的宽高自适应
  saleInstanceBar.resize();
};
//更新报表样式
watch([() => typeSelect.value, () => dateSelect.value, () => pd.orderSaleLine.costMoney, () => pd.orderBuyLine.costMoney],
  ([typeValue]) => {
  if (typeValue === '销货') {
    saleInstanceBar.setOption({
      xAxis : [
        {
          data : pd.instance.data,
        }
      ],
      series : [{
          data: pd.orderSaleLine.totalMoney,
        },{
          data: pd.orderSaleLine.discountMoney,
        },{
          data: pd.orderSaleLine.costMoney,
        }]
    })
  } else if (typeValue === '购货') {
    saleInstanceBar.setOption({
      xAxis : [
        {
          data : pd.instance.data,
        }
      ],
      series : [{
        data: pd.orderBuyLine.totalMoney,
      },{
        data: pd.orderBuyLine.discountMoney,
      },{
        data: pd.orderBuyLine.costMoney,
      }]
    })
  }
},{deep:true})
//按类别更新报表数据
watch(()=>typeSelect.value,(typeValue)=>{
  if (typeValue === '销货') {
    if (pd.orderSaleLine.costMoney.length == 0){
      pd.queryParams.typeIds = pd.saleId;
      getList();
    }
  }else if(typeValue === '购货'){
    if (pd.orderBuyLine.costMoney.length == 0) {
      pd.queryParams.typeIds = pd.buyId;
      getList();
    }
  }
},{deep:true})
//按日期更新报表数据
watch(()=>dateSelect.value,(dateValue)=>{
  pd.instance.data = []
  if (dateValue === '近一周') {
    dataRange(7,true);
    dataXAxis(7,true);
    pd.queryParams.dateRange = '%Y-%m-%d';
    getList();
  }else if(dateValue === '近一月'){
    dataRange(30,true);
    dataXAxis(30,true);
    pd.queryParams.dateRange = '%Y-%m-%d';
    getList();
  }else if (dateValue === '近一年'){
    dataRange(12,false);
    dataXAxis(12,false);
    pd.queryParams.dateRange = '%Y-%m';
    getList();
  }
},{deep:true})

//按类别更新消息数据
watch(()=>msgSelect.value,(msgValue)=>{
  if (msgValue === '销售新增') {
    if (pd.msg.msgCount[0].num == 0){
      pd.msg.queryParams.typeIds = pd.msg.msgId.msgId;
      getMsgList();
    }
  }else if(msgValue === '退货新增'){
    if (pd.msg.msgCount[1].num == 0){
      pd.msg.queryParams.typeIds = pd.msg.msgId.msgId;
      getMsgList();
    }
  }else if(msgValue === '预警信息') {
    getWWPNum();
  }
},{deep:true})
//按日期更新消息数据
watch(()=>msgDateSelect.value,(dateValue)=>{
  if (dateValue === '近一周') {
    msgDataRange(7,true);
    pd.msg.queryParams.dateRange = '%Y-%m-%d';
    pd.msg.queryParams.typeIds = pd.msg.msgId.msgId;
    getMsgList();
  }else if(dateValue === '近一月'){
    msgDataRange(30,true);
    pd.msg.queryParams.dateRange = '%Y-%m-%d';
    pd.msg.queryParams.typeIds = pd.msg.msgId.msgId;
    getMsgList();
  }else if (dateValue === '近一年'){
    msgDataRange(12,false);
    pd.msg.queryParams.dateRange = '%Y-%m';
    pd.msg.queryParams.typeIds = pd.msg.msgId.msgId;
    getMsgList();
  }
},{deep:true})

//获取数据
async function getList(){
  await getOrderList(pd.queryParams).then(res => {
    pd.orderList = res.rows;
    dayData();
  })
  await getProductOrderSort(pd.queryParams).then(res => {
    pd.productSort = res.rows;
  })
}
//获取销售数据
async function getMsgList(){
  await getOrderMsgList(pd.msg.queryParams).then(res => {
    const msgList = res.rows;
    pd.msg.inOutCount.msg1.forEach(item=>{
      let notExists = true;
      msgList.forEach(item2=>{
        if (item.order == item2.typeId && item2.msgNumber){
          item.num = item2.msgNumber;
          notExists = false;
        }
      });
      if (notExists) item.num = 0;
    });
    pd.msg.msgCount.forEach(item => {item.num = 0})
    pd.msg.msgCount.forEach(item => {
      msgList.forEach(item2 => {
        if (item2.typeId && item2.msgNumber && item.typeId.includes(item2.typeId)){
          item.num += item2.msgNumber;
        }
      })
    })
  })
}

//获取库存预警数据
async function getWWPNum(){
  await getWWP().then((res:any) => {
    let num = 0;
    if (res.rows[0].warnTotal){
      num = res.rows[0].warnTotal;
    }
    pd.msg.warnMsgCount.stockWarnMsg.num = num;
  })
}

//将检索的数据按日期归纳
function dayData(){
  pd.orderSaleLine.costMoney = [];
  pd.orderSaleLine.totalMoney = [];
  pd.orderSaleLine.discountMoney = [];
  pd.orderBuyLine.costMoney = [];
  pd.orderBuyLine.totalMoney = [];
  pd.orderBuyLine.discountMoney = [];
  pd.instance.data.forEach(item => {
    const indexVal = pd.instance.data.indexOf(item);
    pd.orderList.forEach(item2 => {
      const date = item2.date.split(" ")[0].split("-");
      date[1] = date[1].replace(/^0/, ''); // 只替换前导零
      let day: string
      if (dateSelect.value == "近一年"){
        day = date[0].slice(2,4)+"年" + date[1]+"月";
      }else{
        date[2] = date[2].replace(/^0/, ''); // 只替换前导零
        day = date[1]+"月"+date[2]+"日";
      }
      if (item == day && item2.costMoney){
        pd.orderList.splice(pd.orderList.indexOf(item2),1);
        if (pd.queryParams.typeIds == pd.saleId){
          pd.orderSaleLine.costMoney[indexVal] = item2.costMoney;
          pd.orderSaleLine.totalMoney[indexVal] = item2.totalMoney;
          pd.orderSaleLine.discountMoney[indexVal] = item2.discountMoney;
        }else if (pd.queryParams.typeIds == pd.buyId){
          pd.orderBuyLine.costMoney[indexVal] = item2.costMoney;
          pd.orderBuyLine.totalMoney[indexVal] = item2.totalMoney;
          pd.orderBuyLine.discountMoney[indexVal] = item2.discountMoney;
        }
      }
    })
    if (pd.queryParams.typeIds == pd.saleId){
      if (pd.orderSaleLine.costMoney[indexVal] == undefined)
        pd.orderSaleLine.costMoney[indexVal] = 0;
      if (pd.orderSaleLine.totalMoney[indexVal] == undefined)
        pd.orderSaleLine.totalMoney[indexVal] = 0;
      if (pd.orderSaleLine.discountMoney[indexVal] == undefined)
        pd.orderSaleLine.discountMoney[indexVal] = 0;
    }else if (pd.queryParams.typeIds == pd.buyId){
      if (pd.orderBuyLine.costMoney[indexVal] == undefined)
        pd.orderBuyLine.costMoney[indexVal] = 0;
      if (pd.orderBuyLine.totalMoney[indexVal] == undefined)
        pd.orderBuyLine.totalMoney[indexVal] = 0;
      if (pd.orderBuyLine.discountMoney[indexVal] == undefined)
        pd.orderBuyLine.discountMoney[indexVal] = 0;
    }
    if (pd.orderList.length == 0){
      return;
    }
  })
}

function formatDate(date:any) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
//检索数据的日期范围，默认是近7天内
function dataRange(day: number, isYear: boolean){
  const currentDate = new Date();
  if (isYear){
    currentDate.setDate(currentDate.getDate() + 1);
    pd.queryParams.params.endCreateTime = formatDate(currentDate);
    const sevenDaysAgo = new Date(currentDate);
    sevenDaysAgo.setDate(currentDate.getDate() - day);
    pd.queryParams.params.beginCreateTime = formatDate(sevenDaysAgo);
  }else{
    currentDate.setDate(currentDate.getDate() + 1);
    pd.queryParams.params.endCreateTime = formatDate(currentDate);
    const twelveMonthsAgo  = new Date(currentDate);
    twelveMonthsAgo.setMonth(currentDate.getMonth() - 12);
    pd.queryParams.params.beginCreateTime = formatDate(twelveMonthsAgo );
  }
}
function msgDataRange(day: number, isYear: boolean){
  const currentDate = new Date();
  if (isYear){
    currentDate.setDate(currentDate.getDate() + 1);
    pd.msg.queryParams.params.endCreateTime = formatDate(currentDate);
    const sevenDaysAgo = new Date(currentDate);
    sevenDaysAgo.setDate(currentDate.getDate() - day);
    pd.msg.queryParams.params.beginCreateTime = formatDate(sevenDaysAgo);
  }else{
    currentDate.setDate(currentDate.getDate() + 1);
    pd.msg.queryParams.params.endCreateTime = formatDate(currentDate);
    const twelveMonthsAgo  = new Date(currentDate);
    twelveMonthsAgo.setMonth(currentDate.getMonth() - 12);
    pd.msg.queryParams.params.beginCreateTime = formatDate(twelveMonthsAgo );
  }
}
//X轴下标
function dataXAxis(dayBefore: number, isYear: boolean){
  const currentDate = new Date();
  if (isYear){
    for (let i = 0; i < dayBefore; i++) {
      const sevenDaysAgo = new Date(currentDate);
      sevenDaysAgo.setDate(currentDate.getDate() - i);
      const month = String(sevenDaysAgo.getMonth() + 1);
      const day = String(sevenDaysAgo.getDate());
      pd.instance.data.push(`${month}月${day}日`)
    }
  }else{
    for (let i = 0; i < dayBefore; i++) {
      const monthDate = new Date(currentDate);
      monthDate.setMonth(currentDate.getMonth() - i);
      // 获取月份名称，月份从 0 开始，因此需要加 1
      const year = String(monthDate.getFullYear()).slice(2,4);
      const month = String(monthDate.getMonth() + 1);
      pd.instance.data.push(`${year}年${month}月`)
    }
  }
  pd.instance.data.reverse();
}

function formatter(row:any, column:any, cellValue:any){
  // 使用 Intl.NumberFormat 对象进行数字格式化
  const formatter = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD', // ￥符号对应的是CNY，这里用USD只是为了格式化
    minimumFractionDigits: 2,
  });

  // 将数值转为字符串，然后替换为CNY格式
  return formatter.format(cellValue).replace('$', '￥');
}

function route(routePath:string,routeQuery:{}){
  router.push({
    path:routePath,
    query:routeQuery
  })
}

/**
 * 库存饼状图
 * */
let stockInstancePie = <any>({});
function pieSet() {
  stockInstancePie = echarts.init(stockPie.value, "macarons");
  stockInstancePie.setOption({
    title: {
      text: '库存',
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      top: '10%',
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '库存数量',
        type: 'pie',
        radius: ['40%', '70%'],
        minAngle: 3, // 设置最小显示角度
        // avoidLabelOverlap: false,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2
        },
        emphasis: {
          label: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: pd.stockPie.stockList,
      }
    ]
  })
}
//获取库存信息
async function getStock(){
  await getStockList().then((res:any)=>{
    pd.stockPie.stockList = res.rows;
    pieSet();
  })
}

/**
 * 收支饼状图
 * */
let billInstancePie = <any>({});
function billPieSet() {
  billInstancePie = echarts.init(billPie.value);
  billInstancePie.setOption({
    title: {
      text: '收支',
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      top: '10%',
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '收支',
        type: 'pie',
        radius: ['40%', '70%'],
        minAngle: 3, // 设置最小显示角度
        avoidLabelOverlap: false,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2
        },
        emphasis: {
          label: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: pd.billPie.billList,
      }
    ]
  })
}

async function getBill(){
  await getBillList(pd.billPie.billQueryParams).then((res:any)=>{
    pd.billPie.billList = res.rows;
    billInstancePie.setOption({
      series: [
        {data: pd.billPie.billList,}
      ]
    })
  })
}
function billDataRange(day: number, isYear: boolean){
  const currentDate = new Date();
  if (isYear){
    currentDate.setDate(currentDate.getDate() + 1);
    pd.billPie.billQueryParams.params.endCreateTime = formatDate(currentDate);
    const sevenDaysAgo = new Date(currentDate);
    sevenDaysAgo.setDate(currentDate.getDate() - day);
    pd.billPie.billQueryParams.params.beginCreateTime = formatDate(sevenDaysAgo);
  }else{
    currentDate.setDate(currentDate.getDate() + 1);
    pd.billPie.billQueryParams.params.endCreateTime = formatDate(currentDate);
    const twelveMonthsAgo  = new Date(currentDate);
    twelveMonthsAgo.setMonth(currentDate.getMonth() - 12);
    pd.billPie.billQueryParams.params.beginCreateTime = formatDate(twelveMonthsAgo );
  }
}

//按日期更新Bill数据
watch(()=>billDateSelect.value,(dateValue)=>{
  if (dateValue === '近一周') {
    billDataRange(7,true);
    getBill();
  }else if(dateValue === '近一月'){
    billDataRange(30,true);
    getBill();
  }else if (dateValue === '近一年'){
    billDataRange(12,false);
    getBill();
  }
},{deep:true})

/**
 * 账户余额柱状图
 * */
let accountInstanceBar = <any>({});
function accountBarSet() {
  accountInstanceBar = echarts.init(accountBar.value);
  accountInstanceBar.setOption({
    title: {
      text: '账户余额',
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    barMaxWidth: 40,
    calculable : true,
    xAxis: [
      {
        type: 'category',
        data: pd.accountBar.xAxisData,
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis : [
      {
        type : 'value',
        axisLabel : {
          formatter: '{value} ￥'
        },
      }
    ],
    itemStyle:{
      borderRadius:[5, 5 , 0, 0],
    },
    series: [
      {
        name: 'Direct',
        type: 'bar',
        barWidth: '60%',
        data: pd.accountBar.seriesData
      }
    ]
  })
}

async function getAccount(){
  pd.accountBar.xAxisData = [];
  pd.accountBar.seriesData = [];
  await getFmsAccount().then((res:any)=>{
    const data = res.rows;
    for (let i = 0; i < data.length; i++) {
      pd.accountBar.xAxisData.push(data[i].name);
      pd.accountBar.seriesData.push(data[i].value);
    }
    accountInstanceBar.setOption({
      xAxis: [
        {
          data: pd.accountBar.xAxisData,
        }
      ],
      series: [
        {
          data: pd.accountBar.seriesData
        }
      ]
    });
  })
}
async function firstRefresh(){
  pd.reloading.firstReloading = true;
  await Promise.all([getMsgList(),getWWPNum()]);
  pd.reloading.firstReloading = false;
}
async function secondRefresh(){
  pd.reloading.secondReloading = true;
  await Promise.all([getList()]);
  pd.reloading.secondReloading = false;
}
async function thirdRefresh(){
  pd.reloading.thirdReloading = true;
  await Promise.all([getStock(),getBill(),getAccount()]);
  pd.reloading.thirdReloading = false;
}

onMounted(() => {
  dataXAxis(7,true);
  dataRange(7, true);
  pd.queryParams.typeIds = pd.saleId;
  getList();
  barSet();

  msgDataRange(7, true);
  pd.msg.queryParams.typeIds = pd.msg.msgId.msgId;
  getMsgList();

  getWWPNum();

  getStock();

  billDataRange(7,true);
  billPieSet();
  getBill();

  accountBarSet();
  getAccount();
});
</script>

<style scoped lang="scss">
.el-badge{
  margin-right: 25px;
}
::v-deep(.el-radio-button .el-radio-button__inner){
  box-shadow: none;
  border-color: rgba(255, 255, 255, 0);
  border-radius: 0;
  padding: 10px 10px;
}
::v-deep(.el-radio-button__original-radio:checked+.el-radio-button__inner){
  box-shadow: none;
  border-radius: 0;
  border-color: rgba(255, 255, 255, 0);
  background-color: rgba(255, 255, 255, 0);
  color: #409EFF;
  padding: 10px 10px;
  border-bottom-color: #1c84c6;
}
::v-deep(.el-radio-button__original-radio:hover+.el-radio-button__inner){
  color: #00d5c1;
}

.divCard{
  width: 100%;
  height: 100%;
  max-width: 600px;
  max-height: 520px;
  margin-right: 10px;
}

</style>
